package org.benjamin.lending.trusteeship.sumapay;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.*;
import org.benjamin.lending.service.RechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * 充值对接操作
 * @author 黄文杰
 *
 */
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Service("sumaplayRechargeOperation")
public class RechargeOperation extends SumapayAbstractOperation {
	
	private final Logger logger = LogManager.getLogger();
	
	@Autowired
	private RechargeService rechargeService;
	

	@Override
	protected void processRequest(Map<String, Object> requestMap, MemberInfo memberInfo, BorrowInfo borrowInfo,Map<String, Object> parameterMap) {
		String bankCode = parameterMap.get("bankCode").toString();
		if(bankCode.equals("simple")){
			this.abutmentUrl = this.sumaplayConfig.getServiceName()+"/user/";
		}else{
			requestMap.put("bankCode", bankCode);
			requestMap.put("bankcardTypeFlag", 1);
			this.abutmentUrl = this.sumaplayConfig.getServiceName()+"/user/webBankRecharge_toRecharge";
		}
		BigDecimal amount = new BigDecimal(parameterMap.get("amount").toString());
		requestMap.put("sum", amount);
		requestMap.put("payType", 2);
		parameterMap.put("fee", BigDecimal.ZERO);
		List<Subledger> subledgerList = new ArrayList<Subledger>();
		subledgerList.add(new Subledger(0,requestMap.get("userIdIdentity").toString(),0,amount));
		try{
			requestMap.put("subledgerList",new ObjectMapper().writeValueAsString(subledgerList));
		}catch(JsonProcessingException e){
			logger.error(e.getMessage(),e);
			throw new IllegalArgumentException("分账列表解析JSON失败");
		}

	}

	@Override
	protected void afterRequest(Map<String, Object> parameterMap,MemberInfo memberInfo,BorrowInfo borrowInfo,TrusteeshipRequest trusteeshipRequest) {
		String bankCode = parameterMap.get("bankCode").toString();
		BigDecimal amount = new BigDecimal(parameterMap.get("amount").toString());
		Object feeObject = parameterMap.get("fee");
		BigDecimal fee = BigDecimal.ZERO;
		if(feeObject != null){
			fee = new BigDecimal(feeObject.toString());	
		}
		String createIp = parameterMap.get("createIp").toString();
		RechargeLog rechargeLog = this.rechargeService.createRechargeLog(memberInfo, bankCode, amount, fee, createIp);
		trusteeshipRequest.setType(TrusteeshipType.recharge);
		trusteeshipRequest.setRel(rechargeLog.getId());
		trusteeshipRequest.setTid(1);
	}

	@Override
	protected String signatureRequest(Map<String, Object> requestMap) {
		String[] signatures = this.buildSignature(requestMap, "requestId","merchantCode","userIdIdentity","sum","bankCode","successReturnUrl","failReturnUrl","bankcardTypeFlag","payType","subledgerList");
		requestMap.put("signature",signatures[1]);
		return signatures[0];
	}


	@Override
	protected String[] signatureResponse(Map<String, Object> responseMap) {
		String[] keys = new String[]{"requestId","result","sum","userIdIdentity","userBalance"};
		return this.buildSignature(responseMap,keys);
	}


	@Override
	protected void processResponse(TrusteeshipRequest trusteeshipRequest,Map<String,Object> responseMap){
		super.processResponse(trusteeshipRequest, responseMap);
		String result = responseMap.get("result").toString();
		String createIp = ObjectUtils.toString(responseMap.get("createIp"),"0.0.0.0.0.0.1");
		if(result.equals("00000")){
			this.rechargeService.rechargeSuccess(trusteeshipRequest.getRel(), createIp);
		}else{
			this.rechargeService.rechargeFail(trusteeshipRequest.getRel(), createIp);
		}
	}

}
